#include "../Headers/dis_img_pro.h"  

int tcp_init(const char *ip, int port, int backlog)
{
    puts(ip);
    int fd = socket(PF_INET, SOCK_STREAM, 0);
    if (-1 == fd)
        return fd;
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(port);
    saddr.sin_addr.s_addr = inet_addr(ip);
    int ok = 1;
    if (-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ok, sizeof ok))
    {
        perror("setsockopt");
        return -1;
    }

    if (-1 == bind(fd, (void *)&saddr, sizeof saddr))
        return -1;

    if (-1 == listen(fd, backlog))
        return -1;
    puts("listen...");
    return fd;
}
int tcp_wait(int fd_listen){
    int cnd_server = accept(fd_listen,NULL,NULL);
    ERROR_CHECK_FUN(cnd_server,-1);
    struct sockaddr_in caddr;
    socklen_t len = sizeof caddr;
    int ret = getpeername(cnd_server,(void *)&caddr,&len);
    ERROR_CHECK_FUN(ret,-1);
    printf("ip<%s>prot<%d> connected\n",inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));
    return cnd_server;
}
int epollAdd(int fd, int epfd){
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = fd;
    int ret = epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&event);
    ERROR_CHECK(ret,-1,"epoll_ctl");
    return 0;
}int epollDel(int fd, int epfd){
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = fd;
    int ret = epoll_ctl(epfd,EPOLL_CTL_DEL,fd,&event);
    ERROR_CHECK(ret,-1,"epoll_ctl");
    return 0;
}
